package com.td.server;

import java.io.IOException;
import java.net.Socket;

import com.td.core.communication.Communication;
import com.td.core.communication.MainReciever;
import com.td.core.communication.Sendable;
import com.td.core.communication.obj.Message;
import com.td.core.communication.obj.PlayerInfo;
import com.td.core.communication.obj.PreGameInfo;
import com.td.core.obj.Player;

public class ClientContainer implements MainReciever {
	
	private GameContainer parent;
	
	private Communication communication;
	private PreGameInfo preGameInfo;
	
	public ClientContainer(Socket socket) throws IOException {
		communication = new Communication(socket, this);
		preGameInfo = new PreGameInfo();
		parent = null;
	}
	
	public PreGameInfo getPreGameInfo() {
		return preGameInfo;
	}
	
	public void setPreGameInfo(PreGameInfo preGameInfo) {
		this.preGameInfo = preGameInfo;
	}
	
	public GameContainer getParent() {
		return parent;
	}

	public void setParent(GameContainer parent) {
		this.parent = parent;
	}

	public void start() {
		communication.start();
	}
	
	public void end() {
		communication.end();
	}
	
	public void send(Sendable<?> obj) {
		communication.send(obj);
	}

	public boolean isConnected() {
		return communication.isConnected();
	}
	
	@Override
	public void recieve(Sendable<?> obj) {
		if(obj instanceof PlayerInfo) {
			PlayerInfo temp = (PlayerInfo) obj;
			temp.copyTo(preGameInfo.getMyPlayer());
			return;
		}
		
		if(obj instanceof Player) {
			Player temp = (Player) obj;
			int plNumber = getPreGameInfo().getMyPlayer().getNumber();
			Player player = parent.getGame().getPlayers()[plNumber];
			temp.copyTo(player);
			return;
		}
		
		if(obj instanceof Message) {
			Message msg = (Message) obj;
			switch(msg.getNumber()) {
			case Message.EXIT:
				System.out.println("Player disconnected: "
						+ getPreGameInfo().getMyPlayer().getNumber() + " "
						+ getPreGameInfo().getMyPlayer().getName());
				communication.end();
				break;
			default:
				break;
			}
		}
	}
}
